<?php
/**
 * 监听进程消息事件
*/

namespace event\rpc;

class onMessage
{
    /**
	 * 启动实例
	*/
    public $server;
    
    /**
     *  服务配置
    */ 
    public $config;
    
    /**
     * 接收服务实例
    */
    public function __construct($server, $config) {
        $this->server = $server;
        $this->config = $config;
    }
    
    /**
     * 统一回调入口
    */
    public function run(\Workerman\Connection\TcpConnection $response, $request) {
        $ip = $response->getRemoteIp();
        // 触发限流器
        if (\houze\Limit::run()->ipVif($this->server, $response->id, $ip, 'rpc') == false) {
            return false;
        }

        $this->server = $server;
        
        // 业务挂载
        $this->rpc($server, $response->id, $response, $request);
        
        // 调用二次转发，不做重载
        $on = new \event\server\onMessage($this->server, $this->config);
        $on->run($response, $request);
    }
    
    /**
     * 微服务TCP服务
    */
    private function rpc($server, $fd, $response, $data) {
        // 初始化进程连接ID
        \houze\context\Container::run($this->server->id.$response->id);
        
        // 请求注入容器
        \houze\context\Container::set('server', $server);
        \houze\context\Container::set('fd', $fd);
        \houze\context\Container::set('response', $response);
        
        // 数据解密
        if (\houze\Config::get('rpc.aes_status') == true) {
            $Currency = new \houze\rpc\Currency();
            $data = $Currency->aes_decrypt($data);
            unset($Currency);
        }
        
        
        $data = json_decode($data, true);
        
        # 开始转发路由
        $obj = new \houze\rpc\ServerRoute();
        $obj->start($response, $data);

        // 销毁整个请求级容器
        \houze\context\Container::delete();
    }

}

